package gardienapplet.ihm;

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
import java.util.Properties;
import gardienapplet.net.Superviseur;

public class GardienApplet extends JApplet
{
    private Properties props;
    private boolean isStandalone = false;
    private String urlSuperviseur;
    private String myIPAdresse;
    private int serverPort;
    private Superviseur superviseur;
    private PanneauApplet jPanel1 = new PanneauApplet();

    /**Obtenir une valeur de paramètre*/
    public String getParameter(String key, String def)
    {
	return isStandalone ? props.getProperty(key, def) :(getParameter(key) != null ? getParameter(key) : def);
    }

    /**Construire l'applet*/
    public GardienApplet() {
    }

    public void setStandalone(Properties props)
    {
	this.props = props;
	isStandalone = true;
    }
    /**Initialiser l'applet*/
    public void init()
    {

	try{  urlSuperviseur = this.getParameter("urlsuperviseur", "http://localhost:7080");}
	catch(Exception e) {System.err.println("erreur acquisition parametre: urlSuperviseur  " + e.getMessage());}
	try { serverPort = Integer.parseInt(this.getParameter("numeroport", "7081"));}
	catch(Exception e) {System.err.println("erreur acquisition parametre: serverPort  " + e.getMessage());}

	try
	{
	   UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
	   //UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
	}
	catch(Exception e) {}

	try
	{
	    jbInit();
	}
	catch(Exception e)
	{
	    e.printStackTrace();
	}
	searchMyIPAdresse();
	try
	{
	    superviseur = new Superviseur(urlSuperviseur, serverPort, myIPAdresse);
	}
	catch (Exception e) {System.out.println("erreur creation superviseur  " + e);}
	String myUrl = "http://" + myIPAdresse + ":" + serverPort;
	jPanel1.setParams(myUrl, urlSuperviseur);
    }

    /**Initialiser le composant*/
    private void jbInit() throws Exception
    {
	this.setSize(new Dimension(342, 100));
	jPanel1.setBackground(Color.lightGray);
	jPanel1.setPreferredSize(new Dimension(340, 100));
	this.getContentPane().add(jPanel1, BorderLayout.CENTER);
    }

    /**Démarrer l'applet*/
    public void start()
    {
    }

    /**Arrêter l'applet*/
    public void stop()
    {
	superviseur.shutDown(100);
	superviseur = null;
    }

    /**Détruire l'applet*/
    public void destroy()
    {
	//System.out.println("destroy");
	//System.gc();
    }

    /**Obtenir les informations d'applet*/
    public String getAppletInfo()
    {
	return "Information applet";
    }

    /**Obtenir les informations de paramètre*/
    public String[][] getParameterInfo()
    {
	return null;
    }

    private void searchMyIPAdresse()
    {
	String adresseIP = "";
	if (isStandalone)
	{
	    try
	    {
		adresseIP = java.net.InetAddress.getLocalHost().getHostAddress();
	    }
	    catch (Exception uhe) {System.err.println(uhe.toString());}
	}
	else
	{
	    URL url = getDocumentBase();
	    String protocole = url.getProtocol();
	    //System.out.println("urlDocumentBase: " + url);
	    //System.out.println("protocole: " + protocole);
	    if (protocole.equals("http"))
	    {
		String host = url.getHost();
		int port = url.getPort();
		if (port < 0) port = 80;
		try
		{
		    Socket socket = new Socket(host, port);
		    InetAddress addr = socket.getLocalAddress();
		    adresseIP = addr.getHostAddress();
		    //System.out.println("HostAddress: " + adresseIP);
		}
		catch (IOException ioe){System.err.println(ioe.toString());}
	    }
	    else
	    {
		try
		{
		    adresseIP = java.net.InetAddress.getLocalHost().getHostAddress();
		}
		catch (Exception uhe) {System.err.println(uhe.toString());}
	    }
	}
	if (!adresseIP.equals(""))
	{
	    myIPAdresse = adresseIP;
	}
    }

    public String getMyIPAdresse()
    {
	return myIPAdresse;
    }

//******************************************************************************
//******************************************************************************

    /**Démarrage de l'application en standalone*/
    public static void main(String[] args)
    {
	Properties props = getProperties( args);
	GardienApplet applet = new GardienApplet();
	applet.setStandalone(props);

	AppletContainer frame = new AppletContainer(applet);

	Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
	frame.setLocation((d.width - frame.getSize().width) / 2, (d.height - frame.getSize().height) / 2);
	frame.setState(Frame.ICONIFIED);
	frame.setVisible(true);
    }

    static class AppletContainer extends JFrame
    {
	GardienApplet applet;
	AppletContainer(GardienApplet applet)
	{
	    this.applet = applet;
	    setTitle("Tableau de bord gardien");
	    setResizable(false);
	    getContentPane().add(applet, BorderLayout.CENTER);
	    applet.init();
	    pack();
	    applet.start();
	}

	/**Remplacé, ainsi nous pouvons sortir quand la fenêtre est fermée*/
	protected void processWindowEvent(WindowEvent e)
	{
	    super.processWindowEvent(e);
	    if (e.getID() == WindowEvent.WINDOW_CLOSING)
	    {
		applet.stop();
		System.exit(0);
	    }
	}
    }
/*
    //Initialiseur statique pour le paramètre LookAndFeel
    static
    {
	try {
	    //UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
	    //UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
	}
	catch(Exception e) {
	}
    }
*/
    public static void help()
    {
	System.out.println( "Tableau de bord Gardien v0.9");
	System.out.println( "Copyright (C) 2000,2001,2002  Gilles Petot Software.");
	System.out.println();
	System.out.println( "GardienAcces [-(h)] [properties_file]");
    }


    public static Properties getProperties( String[] args)
    {
	boolean help = false;
	boolean verbose = false;
	String propertyFile = null;
	Properties props = new Properties();
	if( args.length > 2)
	{
	    help = true;
	}
	else if( args.length == 1)
	{
	    if( "-h".equals( args[0])) help = true;
	    else propertyFile = args[0];
	}
	else if( args.length == 2)
	{
	    propertyFile = args[1];
	    if( "-h".equals( args[0])) help = true;
	}
	if( help)
	{
	    help();
	    return null;
	}
	if( propertyFile != null)
	{
	    try
	    {
		File f = new File( propertyFile);
		if( !f.isAbsolute())
		{
		    f = new File( System.getProperty( "user.dir"), f.getPath());
		}
		props.load( new FileInputStream( f));
	    }
	    catch( IOException ioe)
	    {
		System.err.print( "Error reading property file '");
		System.err.print( propertyFile);
		System.err.println( "'.  Using defaults.");
	    }
	}
	return props;
    }

}